package com.manager.common.tcp.encode.impl;

import com.manager.common.tcp.constant.TcpDataType;
import com.manager.common.tcp.encode.BaseEncode;
import io.netty.buffer.ByteBuf;

public class BusinessEncode extends BaseEncode {

    public BusinessEncode(TcpDataType tcpDataType) {
        setTcpDataType(tcpDataType);
    }

    public BusinessEncode(int code) {
        setTcpDataType(TcpDataType.getTcpDataType(code));
    }

    @Override
    public byte[] encode(String data) throws Exception{

        byte[] bytes = data.getBytes("UTF-8");
        ByteBuf buf = this.head(getTcpDataType());

        buf.writeInt(bytes.length);
        buf.writeBytes(bytes);

        byte[] result = new byte[buf.readableBytes()];
        buf.readBytes(result);

        return result;
    }
}
